package com.xia.minio.controller;

import com.xia.minio.entity.FileItem;
import com.xia.minio.enums.FileType;
import com.xia.minio.service.FileService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import io.minio.GetObjectResponse;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/upload")
public class FileController {

    private final FileService fileService;

    /**
     * 上传图片
     * @param file
     * @return
     */
    @PostMapping("/image/upload")
    public String uploadImage(@RequestParam("file") MultipartFile file) throws Exception {
        String name = fileService.uploadImage(file);
        return name;
    }

    /**
     * 上传文件
     * @param file
     * @return
     */
    @CrossOrigin
    @PostMapping("/file/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
        String name = fileService.uploadFile(file);
        return name;
    }

    /**
     * 上传文件
     * @param files
     * @return
     */
    @CrossOrigin
    @PostMapping("/files/upload")
    public List<String> uploadFiles(@RequestParam("files") MultipartFile[] files) throws Exception {
        List<String> list = new ArrayList<>();
        for (MultipartFile file : files) {
            String name = fileService.uploadFile(file);
            list.add(name);
        }
        return list;
    }

    /**
     * 列出文件列表
     * @param path 路径前缀（可选）
     * @return 文件列表
     */
    @CrossOrigin
    @GetMapping("/list")
    public List<String> listFiles(@RequestParam(required = false) String path) {
        return fileService.listFiles(path);
    }
    
    /**
     * 列出文件项列表（包含详细信息）
     * @param path 路径前缀（可选）
     * @return FileItem对象列表
     */
    @CrossOrigin
    @GetMapping("/list/items")
    public List<FileItem> listFileItems(@RequestParam(required = false, defaultValue = "") String path) {
        return fileService.listFileItems(path);
    }

    /**
     * 列出指定类型的文件
     * @param fileType 文件类型（FILE, IMAGE, VIDEO）
     * @return 文件列表
     */
    @CrossOrigin
    @GetMapping("/list/type")
    public List<String> listFilesByType(@RequestParam String fileType) {
        return fileService.listFilesByType(FileType.valueOf(fileType));
    }
    
    /**
     * 删除文件
     * @param path 文件路径
     * @return 删除结果
     */
    @CrossOrigin
    @DeleteMapping("/delete")
    public boolean deleteFile(@RequestParam String path) {
        return fileService.deleteFile(path);
    }
    
    /**
     * 下载文件
     * @param path 文件路径
     * @param response HttpServletResponse
     */
    @CrossOrigin
    @GetMapping("/download")
    public void downloadFile(@RequestParam String path, HttpServletResponse response) {
        try {
            // 获取文件流
            GetObjectResponse fileStream = fileService.downloadFile(path);
            if (fileStream == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            
            // 设置响应头
            response.setContentType("application/octet-stream");
            // 从路径中提取实际的文件名（最后一个/后面的部分）
            String actualFileName = path.substring(path.lastIndexOf("/") + 1);
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(actualFileName, "UTF-8"));
            
            // 将文件流写入响应
            try (InputStream inputStream = fileStream; OutputStream outputStream = response.getOutputStream()) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.flush();
            }
        } catch (Exception e) {
            log.error("下载文件失败: {}", e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
    
    /**
     * 创建文件夹
     * @param path 文件夹路径
     * @return 创建结果
     */
    @CrossOrigin
    @PostMapping("/folder/create")
    public boolean createFolder(@RequestParam String path) {
        return fileService.createFolder(path);
    }
}